package net.xi.dmhome.config.realms;

import net.xi.dmhome.entity.User;
import net.xi.dmhome.mapper.UserMapper;
import net.xi.dmhome.mapper.UsertypeMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author: jxhu
 * @Description:自定义realm
 * @Date Created in 2021-02-03 11:58
 * @Modified By:
 */
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    UserMapper userMapper;
    @Autowired
    UsertypeMapper usertypeMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//拿到user对象

        //设置当前用户的权限

        String roles = usertypeMapper.getuserPerms(currentUser.getType());
        Set<String> set = new HashSet<>();
        //需要将 role 封装到 Set 作为 info.setRoles() 的参数
        set.add(roles);
        //设置该用户拥有的角色
        info.setRoles(set);
        return info;
    }

    /* @Description: 认证,@Param:  */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {



        //获取token信息
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //查询数据库
        User user = userMapper.selectByEmail(userToken.getUsername());

        if (user != null) {
            //获取shiro当前用户
            Subject currentUser = SecurityUtils.getSubject();
            /*将获取到的用户封装到shiro自己设定的session中，用以提供给LoginController
            再由controller传给前端*/
            Session session = currentUser.getSession();
            session.setAttribute("loginUser",user);

        } else {
            //return null即抛出LoginController中的UnknownAccountException异常
            return null;
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
